/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crane.webtemplate;

import java.io.*;
import java.net.URLEncoder;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.crane.webtemplate.dao.ImageFileDAO;
import org.crane.webtemplate.model.ImageFile;
import org.crane.webtemplate.util.MetaTypeHelp;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *send back the specified file based on the 'id' param
 * @author Crane Leeon
 * @version
 */
public class GetImg extends HttpServlet {

    protected static final Log logger = LogFactory.getLog(GetImg.class);

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isthumbnail = Boolean.parseBoolean(request.getParameter("thumbnail"));
        String contextPath = request.getContextPath();
        String ErrorPageURI = "/WEB-INF/jsp/json.jsp";
        String id = request.getParameter("id");
        String code = request.getParameter("code");
        ServletOutputStream out = null;
        InputStream in = null;
        ImageFileDAO dao = null;
        try {
            dao = new ImageFileDAO();
            ImageFile rfile = null;
            if (id != null && !id.isEmpty()) {
                rfile = (ImageFile) dao.get(Long.parseLong(id));
            } else if(code != null && !code.isEmpty()) {
                rfile = (ImageFile) dao.getByCode(code);
            }
            if(rfile == null){
//                response.setCharacterEncoding("UTF-8");
//                response.setContentType("text/JSON");
//                response.getWriter().print(new JSONObject().put("success", false).put("info", "no such file").toString());
                request.setAttribute("json", new JSONObject().put("success", false).put("info", "no such file").toString());
                request.getRequestDispatcher(ErrorPageURI).forward(request, response);
                return;
            }
            long size = 0;
            String head_user_agent = request.getHeader("user-agent");
            String filename = "";
            if (head_user_agent.indexOf("MSIE") > -1 || head_user_agent.indexOf("Chrome") > -1) {
                response.setCharacterEncoding("UTF-8");
                filename = URLEncoder.encode(rfile.getName(), "UTF-8");
            }else if(head_user_agent.indexOf("Firefox") > -1){
                response.setCharacterEncoding("ISO-8859-1");
                filename = new String(rfile.getName().getBytes("UTF-8"), "ISO-8859-1");
            }else{
                response.setCharacterEncoding("UTF-8");
                filename = rfile.getName();
            }
            if (isthumbnail) {
                response.setContentType(MetaTypeHelp.getMetaType("gif"));
                response.addHeader("Content-Disposition", "attachment; filename=" + filename + "_s.gif");
                response.addHeader("Content-Length", "" + rfile.getThumbnailSize());
                in = rfile.getThumbnailInputStream();
                size = rfile.getThumbnailSize();
            } else {
                response.setContentType(rfile.getType());
                response.addHeader("Content-Disposition", "attachment; filename=" + filename);
                response.addHeader("Content-Length", "" + rfile.getSize());
                in = rfile.getInputStream();
                size = rfile.getSize();
            }
            out = response.getOutputStream();
            for (long i = 0; i < size; i++) {
                out.write(in.read());
            }
            out.flush();
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (Exception ex) {
            logger.debug(ex);
            try {
                request.setAttribute("json", new JSONObject().put("success", false).put("info", ex.getMessage()).toString());
                request.getRequestDispatcher(ErrorPageURI).forward(request, response);
            } catch (JSONException ex1) {
                logger.debug(ex1);
            }
        } finally {
        }


    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "send back the specified file based on the 'id' or 'code' param";
    }
    // </editor-fold>
}
